<template>
    <div class="container autoGrow flex-row">
        <div class="choose-type flex-column">
            <div class="layui-card flex-column choose-account-card">
                <div class="layui-card-header">选择客服账号</div>
                <div class="layui-card-body choose-account-list">
                    <label @click="accountChange(item)" :class="{ 'flex-row account-item':true,'selected': accountChecked.id === item.id }" v-for="(item) in accounts" :key="item.id">
                        <friend
                            :avatar="item.avatar"
                            :name="item.name"
                            :wxid="item.wxid"
                            :gender="item.gender"
                            class="account-item-friend"
                        />
                    </label> 
                </div>
            </div>


        </div>
        <div class="choose-message flex-column">
            <div class="layui-card flex-column">
                <div class="layui-card-header">关键词设置</div>
                <div class="layui-card-body">
                    <div class="layui-form">
                        <textarea name="desc" v-model="keyword" placeholder="请输入关键词，多个关键词换行" class="layui-textarea"></textarea>
                    </div>    
                </div>
                
            </div> 
            <div class="layui-card flex-column" style="height:100%">
                <div class="layui-card-header">回复设置</div>
                <div class="layui-card-body replies">
                    <messageButtonGroup 
                        :csid="csid"
                        :wxid="accountChecked.wxid"
                        @create="createReply"
                        :types="['text','image','video','link','file','card','document','forward']"
                    /> 
                    <div class="quick-plane">
                        <div class="quick-item" v-for="(reply, index) in replys" :key="index">
                        <div class="quick-item-createtime" style="text-align:right">
                            <i @click.stop="replys.splice(index,1)" class="el-icon-close quick-item-close"></i>
                        </div>
                        <messageCard :message="reply" />
                        </div>
                    </div> 
                </div>
                
            </div>  
            <button type="button" @click="submitSend" class="layui-btn layui-btn-fluid">提交</button>
        </div>
        <div class="detail-container autoGrow flex-column">
            <fieldset><legend><span name="fieldset">关键词回复记录</span></legend></fieldset>
            <template v-if="records.length">
                <el-collapse accordion v-model="accordion">
                    <el-collapse-item class="detail-item" v-for="(record,index) in records" :key="record.id" :name="index+''">
                        <div slot="title" class="flex-row detail-content">
                            <img class="detail-avatar" :src="accountChecked.avatar" />
                            <div class="flex-column detail-info">
                                <span class="detail-keyword">关键词：<span style="color:#FF5722">{{record.keyword}}</span></span>
                                <span class="fontGrey">{{formatTime(record.createTime)}} 配置</span>
                            </div>
                            <div>
                                <button type="button" class="layui-btn layui-btn-sm" @click="showDetail(record)">详情</button>
                                <button type="button" class="layui-btn layui-btn-sm layui-btn-danger" @click.stop="deleteRecord(record)">删除</button>
                            </div>
                        </div>
                        <div class="layui-tab layui-tab-card detail-setting">
                            <ul class="layui-tab-title">
                                <li class="layui-this">回复记录</li>
                                <li>回复内容</li>
                            </ul>
                            <div class="layui-tab-content">
                                <div class="layui-tab-item layui-show">
                                    <div class="detail-setting-list" v-if="record.wxReplyRecord.length && record.wxReplyRecord[0].friends && record.wxReplyRecord[0].friends[0]">

                                        <label class="flex-row account-item detail-setting-item" v-for="item in record.wxReplyRecord" :key="item.id">
                                            <friend
                                                v-if="item.friends[0]"
                                                :name="item.friends[0].friendnick"
                                                :avatar="item.friends[0].avatar"
                                                :gender="item.friends[0].friendsex"
                                                :wxid="item.friends[0].friendwxid"
                                            />
                                            <span class="fontGrey account-item-time">
                                                {{ formatTime(item.createtime) }}
                                            </span>
                                            <button @click="toChat(item)" type="button" class="layui-btn layui-btn-sm">查看</button>
                                        </label> 
                                        
                                    </div>
                                    <div class="data-empty" v-else>
                                        <span class="fontGrey">暂无数据</span>
                                    </div>
                                    
                                </div>
                                <div class="layui-tab-item">
                                    <div class="detail-setting-list">
                                        <div class="detail-record-content">
                                            <messageButtonGroup 
                                                :csid="csid"
                                                :wxid="accountChecked.wxid"
                                                @create="editMessage"
                                            /> 
                                            <div class="quick-plane">
                                                <div class="quick-item" v-for="(reply, index) in editRecord.id === record.id?editRecord.messages:record.messages" :key="index">
                                                <div class="quick-item-createtime" style="text-align:right">
                                                    <i @click.stop="editRecord.messages.splice(index,1)" class="el-icon-close quick-item-close"></i>
                                                </div>
                                                <messageCard :message="reply" />
                                                </div>
                                            </div> 
                                        </div>
                                        <div class="detail-setting-ctrl">
                                            <button type="button" @click="submitEdit(editRecord)" class="layui-btn layui-btn-sm layui-btn-normal" >提交</button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </el-collapse-item>
                </el-collapse>
                
            </template>
            <template v-else>
                <div class="data-empty">
                    <span class="fontGrey">暂无数据</span>
                </div>                        
            </template>
        </div>
    </div>        
</template>
<script>
import friend from '@/components/friend'
import group from '@/components/group'
import QuickReplies from './quickReplies';
import message from '@/components/message'
import { mapState, mapActions, mapMutations } from 'vuex';
import { getChatid,getAccountid } from '@/lib/data-translate'
import messageButtonGroup from '@/components/message-button-group'
import messageCard from '@/components/message-card'

export default {
    name:'autoreply' ,
    data(){
        return {
            accountChecked:{},
            keyword:'',
            reply:null,
            replys:[],
            records:[],
            editcontent:{},
            editRecord:{},
            accordion:''
        }
    },
    mounted(){
        if(this.accounts.length){
            this.accountChange(this.accounts[0])   
        }   
    },
    components:{
        friend,group,QuickReplies,message,
        messageButtonGroup,
        messageCard
    },
    watch:{
        accordion(val,old){
            this.chooseMessageRecord(val)
        },
        accounts(accounts){
            if(accounts.length){
                this.accountChange(accounts[0])   
            }
        }
    }, 
    computed:{
        ...mapState(['accountMap','accountListMap','uistate']),
        accounts(){
            const {adminid} = this.uistate
            if( adminid ===-1 || !this.accountListMap[adminid] )return []
            const accounts = this.accountListMap[adminid].map(id=>{
                const item = this.accountMap[id]
                return {
                    id:item.id,
                    csid:item.csid,
                    name:item.nick,
                    avatar:item.avatar,
                    wxid:item.wxid,
                    gender:item.gender
                }
            })
            return accounts
        } ,
        csid(){
            return this.uistate.adminid
        }
    },
    methods:{
        ...mapMutations(['updateUIState']),
        ...mapActions(['addChatByFriend','requestChatMap']),
        requestList(){
            const account = this.accountChecked
            const csid = this.uistate.adminid
            if(csid === -1 || !account)return;
            this.$api.keyword.list({
                csId:csid,
                wxAccount: account.wxid,
                type:1
            }).then(data=>{
                this.records = data.map(item=>{
                    const _msgcontent = JSON.parse(item.msgcontent)
                    let messages = []
                    if(_msgcontent instanceof Array){
                        item.messages = _msgcontent
                    }else{
                        item.messages = [_msgcontent]       
                    }
                    return item
                })
            }).catch(e=>this.$msg(e))
        },
        reset(){
            this.keyword = ''
            this.replys = []
        },
        chooseMessageRecord(index){
            this.editRecord = index ===''?{}:this.records[+index]
            console.log(this.editRecord)
        },
        deleteMessage(record){
            this.editcontent[record.id] = ''
        },
        editMessage(message){
            console.log('editMessage')
            this.editRecord.messages.push(message)  
        },
        accountChange(account){
            this.accountChecked = account 
            this.accordion = ''
            this.requestList()
        },
        chooseMessage(message) {
            if(!message.length)return;
            const reply = message[message.length-1]
            this.reply = reply
        },
        createReply(reply){
            this.replys.unshift(reply)
        },
        submitSend() {
            const keyword = this.keyword.trim()
            const account = this.accountChecked
            const csid = this.uistate.adminid
            const replys = [...this.replys]
            if(!account.id)return this.$msg('请选择客服账号')
            if(!keyword)return this.$msg('请输入关键词')
            if(!replys.length) return this.$msg("请选择回复的内容")

            const _keyword = keyword.split('\n').filter(str=>str.trim()!=='').map(str=>str.trim()) 

            this.$api.keyword.insert({
                csid,
                wxaccount: account.wxid,
                keyword:_keyword.join(','),//this.keywords.filter(word=>word.trim()!='').join(','),
                msgcontent: JSON.stringify(replys.reverse()),
                // replyType: this.reply.msgtype,
                type:1
            }).then(rs=>{
                this.$msg('添加成功')
                const _msgcontent = JSON.parse(rs.msgcontent)
                let messages = []
                if(_msgcontent instanceof Array){
                    rs.messages = _msgcontent
                }else{
                    rs.messages = [_msgcontent]       
                }
                this.records.unshift(rs)
                
                this.reset()

            }).catch(e=>this.$msg(e))
        },
        submitEdit(editRecord){
            if(editRecord.id){
                const { id,csid,wxaccount,keyword,type ,messages } = editRecord;
                if(!messages.length) return this.$msg("请选择回复的内容")
                const msgcontent = JSON.stringify(messages);
                this.$api.keyword.updateSetting({
                    id,csid,wxaccount,keyword,type ,msgcontent   
                }).then(rs=>{
                    this.$msg('修改成功')
                    this.records.forEach(element => {
                        if(element.id === id){
                            element.messages = messages     
                        }    
                    });
                    this.$forceUpdate()
                }).catch(e=>this.$msg)
                console.log(editRecord)
            }
        },
        showDetail(record){
           // record.showDetail = !record.showDetail
            //this.$forceUpdate()
        },
        deleteRecord(record){
            const msg = confirm('确认删除记录？')
            if(msg){
                this.$api.keyword.deleteSetting({
                    id: record.id,
                    type:1
                }).then(()=>{
                    this.records = this.records.filter(item=>item.id !== record.id)
                    this.$msg('删除成功')
                }).catch(e=>this.$msg(e))
            }
        },
        toChat(record){
            const { wxaccountid,groupaccount,csid,friends } = record;
            const accountid = getAccountid(this.accountMap,csid,wxaccountid)
            const chatid = getChatid(csid,accountid,groupaccount)
            const friend = friends[0]

            this.updateUIState({ accountid })
            this.requestChatMap({csid,wxaccount:wxaccountid})
            .then(rs=>{
                if(rs&&rs[0]){
                    this.addChatByFriend({...friend,id:undefined}) // 添加到chat相关
                    this.$router.push({
                        name: 'home',
                    })
                    setTimeout(()=>{
                        this.updateUIState({ chatid })
                    },0)
                    
                }
                 
            })
            // this.addChatByFriend({...friend,id:undefined}) // 添加到chat相关
        }
    },
    

}
</script>
<style scoped>
.container{
    border-top: 1px solid #ccc; 
    height: 100%;
}
.choose-type{
    width: 260px;
    overflow: auto;
    flex-shrink: 0; 
    border-right: 1px solid #ccc; 
    background: #e2e2e2;
    padding: 15px;
    box-sizing: border-box;
}
.choose-message{
    width: 260px;
    height: 100%;
    flex-shrink: 0;
    border-right: 1px solid #ccc; 
    background: #f1f1f1;
    padding: 15px;
    box-sizing: border-box;
}
.account-card{
    height: 100%;
}
.choose-type{
    height:100%;
}
.choose-card{

}
.choose-account-card{
    height:100%;
    /* margin-bottom: 10px; */
}
.choose-account-list{
    height:100%;
    overflow: auto;
    padding: 0;
}
.account-list{
    height:100%;
    overflow: auto
}
.account-item{
    align-items: center;
    padding: 10px;
    cursor: pointer;
}
.account-item.selected{
    background-color: #eee
}
.account-item:last-child{
    margin-bottom: 0
}
.account-item-time{
    flex:1
}
.account-item-friend,
.account-item-group{
    /* margin-left: 5px */
}
.detail-container{
    background-color: #f2f2f2;
    padding:15px;
    box-sizing: border-box;
    height: 100%;
    overflow: auto;
}
.detail-container fieldset {
    border: none;
    padding: 0;
    border-top: 1px solid #ddd;
    margin-bottom: 10px;
} 
.detail-record-content{
    position: relative;
    padding: 0 20px;
    min-height: 50px;
}
.detail-container fieldset legend {
    margin-left: 20px;
    padding: 0 10px;
    font-size: 22px;
    font-weight: 300;
} 
.detail-item{
    padding: 10px 16px;
    background-color: #fff;
    border-radius: 4px;
    border-left: 5px solid #50bfff;
    margin: 5px 0;  
    cursor: pointer; 
}
.detail-item >>> .el-collapse-item__header,
.detail-item >>> .el-collapse-item__wrap{
    border-bottom: 0
}
.detail-item >>> .el-collapse-item__content{
    padding-bottom: 0
}
.detail-avatar{
    width: 40px;
    height: 40px;
    background-color: #ccc;
    box-sizing: border-box;
    border-radius: 3px;
}
.detail-info{
    flex:1;
    padding-left: 10px;
    height: 40px;
    justify-content: center;
    line-height: 20px;
}
.detail-keyword{
    font-size: 16px;
}
.detail-setting{
    margin-top: 10px;
}
.detail-setting .layui-tab-item{
    height: 180px;
}
.data-empty{
    display: flex;
    justify-content: center;
    align-items: center;
    flex: 1;
    height: 100%;
}
.detail-setting .layui-tab-content{
    padding: 0
}
.detail-content{
    align-items: center;
    justify-content: space-between;
    flex:1;
    padding-right: 20px;
}
.detail-setting-list{
    flex: 1;
    height: 100%;
    overflow: auto;
    padding:10px 0;
    box-sizing: border-box;
}
.detail-setting-item{
    margin-bottom: 0
}
.detail-setting-ctrl{
    margin-top:10px;
    margin-right: 10px;
    text-align: right;
}

.replies{
    padding: 10px;
    padding: 10px;
    height: 100%;
    overflow: auto;
}
.quick-item{
    padding: 10px 16px;
    background-color: #fff;
    border-radius: 4px;
    border-left: 5px solid #50bfff;
    margin: 5px 0;  
    cursor: pointer; 
    box-shadow: 0px 1px 1px 1px #ddd;
    transition:transform 200ms;
    padding-right: 10px;
}

</style>